<?php
namespace app\widget\controller;
use app\common\controller\AdminBase;

class ApiAdminWidgetFriendLink extends AdminBase
{
    public function itemAdd()
    {
        $name = input('post.name');
        $url = input('post.url');
        $description = input('post.description');

        if (!$name) {
          return jsonError('请输入名称');
        }
        if (!$url) {
          return jsonError('请输入网址');
        }
        if (!$description) {
            $description = $name;
        }
        $type = input('post.type');
        if (!$type) {
            $type = 'all';
        }
        $createInfo = db('WidgetFriendLink')->insert(array(
           'name' => $name,
           'url' => $url,
           'description' => $description,
           'type' => $type,
           'add_time' => time(),
           'status' => 1,
        ));
        return jsonSuccess('添加成功');
    }
    
    public function itemEdit()
    {
        $id = input('post.id');
        $name = input('post.name');
        $url = input('post.url');
        $description = input('post.description');

        if (!$name) {
          return jsonError('请输入名称');
        }
        if (!$url) {
          return jsonError('请输入网址');
        }
        if (!$description) {
            $description = $name;
        }
        $type = input('post.type');
        if (!$type) {
            $type = 'all';
        }

        if(!$friendlinkInfo = db('WidgetFriendLink')->where('id',$id)->find()) {
            return jsonError('友情链接不存在');
        }
        if(db('WidgetFriendLink')->where('id',$id)->update(['name' => $name, 'url' => $url, 'description' => $description, 'type' => $type])){
            return  jsonSuccess('修改成功');
        }
    }
    
    public function itemDel()
    {
        $id = input('post.id');
        if (!$id) {
          return jsonError('缺少参数');
        }

        $friendlinkInfo = db('WidgetFriendLink')->where('id',$id)->find();
        if ($friendlinkInfo) {
            db('WidgetFriendLink')->where('id',$id)->delete();
            return jsonSuccess('删除成功');
        } else {
            return jsonError('友情链接不存在');
        }
    }
    
    public function itemSortSave()
    {
        $itemList = input('post.itemList/a');
        foreach ($itemList as $key => $val) {
            if (db('WidgetFriendLink')->where('id',$val['id'])->find()) {
                db('WidgetFriendLink')->where('id',$val['id'])->update(array('sort' => $val['sort']));
            }
        }
        return jsonSuccess('保存成功');
    }

    public function itemList()
    {
		$orderBy = input('post.orderBy');
		$order = input('post.order');

		if(!$orderBy){
           $orderBy = 'sort';
		}
		if(!$order){
            $order = 'desc';
		}
	    $friendlinkList = db('WidgetFriendLink')->order($orderBy, $order)->select();
	    return jsonSuccess('',['friendlinkList' => $friendlinkList]);
    }

}